package com.yunshipei.ui.fragment;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.yunshipei.common.manager.EnterConfig;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.db.green.XCloudSign;
import com.yunshipei.db.green.XCloudSignDao;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.EnterDbManager;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.SSOSettingModel;
import com.yunshipei.model.YspEvent;
import com.yunshipei.utils.BaseUtil;
import com.yunshipei.utils.ToastUtils;
import com.yunshipei.utils.encryption.Aes;

import org.xwalk.core.XWalkCookieManager;
import org.xwalk.core.XWalkView;

import butterknife.Bind;
import io.rong.eventbus.EventBus;

public class SWADetailFragment extends BaseBodyFragment {

    private static final String ARGS_SSO_MODEL = "args.sso.model";
    public static final String EXTRA_RESULT_DATA = "sso_result_data_host";

    public static SWADetailFragment newInstance(MainExtraBean mainExtraBean, SSOSettingModel ssoSettingModel) {
        SWADetailFragment swaDetailFragment = new SWADetailFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_CUSTOMER_MAIN_DATA, mainExtraBean);
        bundle.putSerializable(ARGS_SSO_MODEL, ssoSettingModel);
        swaDetailFragment.setArguments(bundle);
        return swaDetailFragment;
    }

    @Bind(R.id.et_title_bar)
    protected YspTitleBar mTitleBar;
    @Bind(R.id.et_sso_user_name)
    protected EditText etUserName;
    @Bind(R.id.et_sso_password)
    protected EditText etPassword;
    @Bind(R.id.et_sso_confrim_password)
    protected EditText etConfirmPassword;
    @Bind(R.id.btn_sso_confirm)
    protected TextView tvSSOConfirm;

    private XCloudSignDao mXCloudSignDao;
    private XCloudSign mXCloudSign;
    private SSOSettingModel mSsoSettingModel;

    private boolean userNameAvailable = false;
    private boolean passwordAvailable = false;
    private boolean confirmPasswordAvailable = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSsoSettingModel = (SSOSettingModel) getArguments().getSerializable(ARGS_SSO_MODEL);
    }

    @Override
    public int viewLayout() {
        return R.layout.fragment_swa_detail;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mTitleBar.setTitle(mSsoSettingModel.getName());
        if (isPad()) {
            mTitleBar.setBackClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BaseUtil.hideKeyBoard(mContext);
                    EventBus.getDefault().post(new YspEvent.SWA());
                }
            });
        }
        mXCloudSignDao = EnterDbManager.getInstances().getXCloudSignDao();
        mXCloudSign = mXCloudSignDao.queryBuilder().where(XCloudSignDao.Properties.Host.eq(mSsoSettingModel.getHost())).build().unique();
        tvSSOConfirm.setOnClickListener(null);
        tvSSOConfirm.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
        tvSSOConfirm.setAlpha(0.6f);
        etUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    userNameAvailable = false;
                    tvSSOConfirm.setAlpha(0.6f);
                    tvSSOConfirm.setOnClickListener(null);
                } else {
                    userNameAvailable = true;
                    if (passwordAvailable && confirmPasswordAvailable) {
                        tvSSOConfirm.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
                        tvSSOConfirm.setAlpha(1f);
                        tvSSOConfirm.setOnClickListener(clickListener);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    passwordAvailable = false;
                    tvSSOConfirm.setAlpha(0.6f);
                    tvSSOConfirm.setOnClickListener(null);
                } else {
                    passwordAvailable = true;
                    if (userNameAvailable && confirmPasswordAvailable) {
                        tvSSOConfirm.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
                        tvSSOConfirm.setAlpha(1f);
                        tvSSOConfirm.setOnClickListener(clickListener);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        etConfirmPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    confirmPasswordAvailable = false;
                    tvSSOConfirm.setAlpha(0.6f);
                    tvSSOConfirm.setOnClickListener(null);
                } else {
                    confirmPasswordAvailable = true;
                    if (passwordAvailable && userNameAvailable) {
                        tvSSOConfirm.setBackgroundColor(EnterConfig.getInstance().getGlobalColor());
                        tvSSOConfirm.setAlpha(1f);
                        tvSSOConfirm.setOnClickListener(clickListener);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        String key = Aes.generateKey(mMainExtraBean.getUserInfo().getUuid());
        if (mXCloudSign != null && !TextUtils.isEmpty(key)) {
            userNameAvailable = true;
            String userName = mXCloudSign.getUserName();
            if (!TextUtils.isEmpty(userName)) {
                String realUserName = "";
                try {
                    realUserName = new String(Aes.decrypt(Aes.decryptBASE64(userName), key));
                } catch (Exception ignored) {
                }
                int len = realUserName.length();
                etUserName.setText(realUserName);
                etUserName.setSelection(len);
            }
            String password = mXCloudSign.getPassword();
            if (!TextUtils.isEmpty(password)) {
                String realPassword = "";
                try {
                    realPassword = new String(Aes.decrypt(Aes.decryptBASE64(password), key));
                } catch (Exception ignored) {
                }
                int len = realPassword.length();
                etPassword.setText(realPassword);
                etPassword.setSelection(len);
                etConfirmPassword.setText(realPassword);
                etConfirmPassword.setSelection(len);
            }
        }
    }

    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String type = String.valueOf(mSsoSettingModel.getType());
            String userName = etUserName.getText().toString().trim();
            String password = etPassword.getText().toString().trim();
            String confirmPassword = etConfirmPassword.getText().toString().trim();
            if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
                ToastUtils.showToast("用户名或密码不能为空");
                return;
            }
            if (!confirmPassword.equals(password)) {
                ToastUtils.showToast("密码不一致");
                return;
            }
            String key = Aes.generateKey(mMainExtraBean.getUserInfo().getUuid());
            String encUserName = "";
            try {
                encUserName = Aes.encryptBASE64(Aes.encrypt(userName.getBytes(), key));
            } catch (Exception ignored) {
            }
            String encPassword = "";
            try {
                encPassword = Aes.encryptBASE64(Aes.encrypt(password.getBytes(), key));
            } catch (Exception ignored) {
            }
            if (!TextUtils.isEmpty(encUserName) && !TextUtils.isEmpty(encPassword)) {
                if (mXCloudSign != null) {
                    mXCloudSign.setUserName(encUserName);
                    mXCloudSign.setPassword(encPassword);
                    mXCloudSign.setExtra1(type);
                    mXCloudSignDao.update(mXCloudSign);
                } else {
                    mXCloudSign = new XCloudSign(mSsoSettingModel.getHost(), encUserName, encPassword, type, "", "");
                    mXCloudSignDao.insert(mXCloudSign);
                }
                XWalkView xWalkView = new XWalkView(mContext);
                xWalkView.onDestroy();
                XWalkCookieManager cookieManager = new XWalkCookieManager();
                String url = mSsoSettingModel.getUrl();
                String cookie = cookieManager.getCookie(url);
                if (!TextUtils.isEmpty(cookie)) {
                    cookieManager.removeAllCookie();
                }
                String host = mXCloudSign.getHost();
                if (isPad()) {
                    BaseUtil.hideKeyBoard(mContext);
                    EventBus.getDefault().post(new YspEvent.SWA());
                    EventBus.getDefault().post(new YspEvent.SWASettingChange(host));
                } else {
                    Intent intent = new Intent();
                    intent.putExtra(EXTRA_RESULT_DATA, host);
                    getActivity().setResult(Activity.RESULT_OK, intent);
                    getActivity().finish();
                }
            }
        }
    };
}
